import React, { useState } from 'react';
import { Typography, Spin, Button, message, Table, Tag, Divider, Modal } from 'antd';
import { CopyOutlined, CheckCircleOutlined, CloseCircleOutlined, ExpandOutlined } from '@ant-design/icons';
import  type { JudgeInfo } from '../../api/vo/problemDetail';

const { Text } = Typography;

interface RunResultProps {
  loading: boolean;
  output: string;
  error: string;
  testCaseInput: string;
  onTestCaseInputChange: (value: string) => void;
  activeTabKey: string;
  onTabChange: (key: string) => void;
  judgeInfo?: JudgeInfo[];
  isOnlineTest?: boolean;
  memory?: number;
  time?: number;
  isAccepted?: boolean;
  outputList?: string[];
}

const RunResult = ({ 
  loading, 
  output, 
  error, 
  activeTabKey,
  judgeInfo = [],
  isOnlineTest = false,
  memory = 0,
  time = 0,
  isAccepted = false
}: RunResultProps) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [modalContent, setModalContent] = useState('');

  // 复制输出到剪贴板
  const copyOutputToClipboard = () => {
    if (!output) {
      message.warning('没有可复制的输出内容');
      return;
    }
    
    navigator.clipboard.writeText(output).then(
      () => {
        message.success('输出内容已复制到剪贴板');
      },
      () => {
        message.error('复制失败，请手动复制');
      }
    );
  };

  // 显示放大的输出内容
  const showExpandedOutput = (content: string) => {
    setModalContent(content);
    setModalVisible(true);
  };

  // 渲染信息栏内容，包含输出信息
  const renderMessageColumn = (message: string, record: any, index: number) => {
    // 优先显示record中的output字段，如果没有output则显示message
    const displayContent = record.output || message;
    
    if (!displayContent) return '-';
     
    // 如果内容超过15个字符，显示截断版本和展开按钮
    if (displayContent.length > 15) {
      return (
        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
          <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {displayContent.substring(0, 15)}...
          </span>
          <Button 
            type="text" 
            size="small" 
            icon={<ExpandOutlined />}
            onClick={() => showExpandedOutput(displayContent)}
            title="点击查看完整内容"
          />
        </div>
      );
    }
    
    return displayContent;
  };



  const renderContent = () => {
    if (activeTabKey === 'result') {
      if (loading) {
        return (
          <div style={{ height: '100%', overflowY: 'auto' }}>
            <div style={{ textAlign: 'center', padding: '20px' }}>
              <Spin tip="代码运行中...">
                <div style={{ minHeight: '50px' }} />
              </Spin>
            </div>
          </div>
        );
      }
      
      // 优先检查在线自测结果，即使有error信息也要显示judgeInfo表格
      if (isOnlineTest && judgeInfo.length > 0) {
        // 在线自测结果显示
        return (
          <div style={{ height: '100%', overflowY: 'auto' }}>
            <div style={{ marginBottom: '16px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                <div>
                  <Tag color={isAccepted ? '#52c41a' : '#f5222d'}>
                    {isAccepted ? 
                      <><CheckCircleOutlined /> 通过</> : 
                      <><CloseCircleOutlined /> 未通过</>
                    }
                  </Tag>
                </div>
                <div>
                  <Text type="secondary" style={{ marginRight: '16px' }}>内存: {memory} KB</Text>
                  <Text type="secondary">时间: {time} ms</Text>
                </div>
              </div>
              
              <Divider style={{ margin: '8px 0' }} />
              
              <Table 
                dataSource={judgeInfo.map((info, index) => ({ ...info, key: index }))} 
                pagination={false}
                size="small"
                style={{ marginBottom: '16px' }}
              >
                <Table.Column title="测试点" dataIndex="key" key="key" render={(text) => `#${text + 1}`} />
                <Table.Column title="结果" dataIndex="result" key="result" 
                  render={(result) => {
                    const getResultTag = (resultCode: number) => {
                      switch (resultCode) {
                        case -1:
                          return <Tag color="#f5222d">失败</Tag>;
                        case 0:
                          return <Tag color="#fa8c16">CE</Tag>;
                        case 1:
                          return <Tag color="#52c41a">AC</Tag>;
                        case 2:
                          return <Tag color="#f5222d">WA</Tag>;
                        case 3:
                          return <Tag color="#fa541c">TLE</Tag>;
                        case 4:
                          return <Tag color="#722ed1">MLE</Tag>;
                        case 5:
                          return <Tag color="#13c2c2">PE</Tag>;
                        case 6:
                          return <Tag color="#eb2f96">RE</Tag>;
                        case 7:
                          return <Tag color="#595959">SE</Tag>;
                        default:
                          return <Tag color="#d9d9d9">未知</Tag>;
                      }
                    };
                    return getResultTag(result);
                  }} 
                />
                <Table.Column title="内存" dataIndex="memory" key="memory" render={(mem) => `${mem} KB`} />
                <Table.Column title="时间" dataIndex="time" key="time" render={(t) => `${t} ms`} />
                <Table.Column title="信息" dataIndex="message" key="message" render={renderMessageColumn} width={200} />
              </Table>
            </div>
          </div>
        );
      }
      
      if (error) {
        return (
          <div style={{ height: '100%', overflowY: 'auto' }}>
            <pre style={{ color: '#ff4d4f', margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all' }}>
              <Text type="danger">{error}</Text>
            </pre>
          </div>
        );
      }
      

      
      // 普通运行结果显示
      return (
        <div style={{ height: '100%', overflowY: 'auto' }}>
          <div style={{ position: 'relative' }}>
            <div style={{ position: 'absolute', top: 0, right: 0, zIndex: 2 }}>
              <Button 
                type="text" 
                size="small" 
                icon={<CopyOutlined />} 
                onClick={copyOutputToClipboard}
                disabled={!output}
              />
            </div>
            <pre style={{ margin: 0, whiteSpace: 'pre-wrap', wordBreak: 'break-all', paddingTop: '4px' }}>
              {output || '暂无输出'}
            </pre>
          </div>
        </div>
      );
    } else if (activeTabKey === 'testCase') {
      return (
        <div style={{ height: '100%', position: 'relative' }}>
          <div style={{ position: 'absolute', top: 0, right: 0, zIndex: 2 }}>
          </div>

        </div>
      );
    }
    return null;
  };

  return (
    <div className="run-result" style={{ height: '100%' }}>
      {renderContent()}
      
      <Modal
        title="完整输出内容"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={[
          <Button key="copy" icon={<CopyOutlined />} onClick={() => {
            navigator.clipboard.writeText(modalContent).then(
              () => message.success('内容已复制到剪贴板'),
              () => message.error('复制失败')
            );
          }}>
            复制
          </Button>,
          <Button key="close" onClick={() => setModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
        style={{ top: 20 }}
      >
        <pre style={{ 
          margin: 0, 
          whiteSpace: 'pre-wrap', 
          wordBreak: 'break-all',
          maxHeight: '60vh',
          overflow: 'auto',
          backgroundColor: '#f5f5f5',
          padding: '12px',
          borderRadius: '4px'
        }}>
          {modalContent}
        </pre>
      </Modal>
     </div>
   );
};

export default RunResult;